﻿using Letter.IO.Buf;
using System;
using System.Collections.Generic;

namespace Beefly.Json.Buffer;

sealed class BufferCache
{
    private const int MAX_SIZE = 16;
    [ThreadStatic]
    private static BufferCache cache;

    public static BufferCache Current()
    {
        if (cache == null)
        {
            cache = new BufferCache();
        }

        return cache;
    }
    
    public BufferCache()
    {
        this.Alloc();
    }

    ~BufferCache()
    {
        foreach (var item in buffers)
        {
            BufferManager.Ret(item);
        }
    }

    private Stack<IBuffer<char>> buffers = new Stack<IBuffer<char>>();

    private void Alloc()
    {
        for (int i = 0; i < 8; i++)
        {
            var buf = BufferManager.Get();
            buffers.Push(buf);
        }
    }

    public IBuffer<char> Get()
    {
        if (this.buffers.Count < 1)
        {
            this.Alloc();
        }

        return buffers.Pop();
    }

    public void Ret(IBuffer<char> buf)
    {
        if (this.buffers.Count >= MAX_SIZE)
        {
            BufferManager.Ret(buf);
        }
        else
        {
            this.buffers.Push(buf);
        }
    }
}
